package com.sixmac.platform;

import com.sixmac.common.base.BaseController;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.grid.BladePage;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.Examin;
import com.sixmac.model.ExaminTopic;
import com.sixmac.model.ExaminTopicAnswer;
import com.sixmac.service.ExaminService;
import com.sixmac.util.ReadExcel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ExaminController 题目列表
 * 2018-07-09 09:19:09
 *
 * @author Blade
 */
@Controller
@RequestMapping("/examin")
public class ExaminController extends BaseController {
    private static String CODE = "examin";
    private static String PREFIX = "t_examin";
    private static String LIST_SOURCE = "examin.list";
    private static String BASE_PATH = "/platform/examin/";

    @Autowired
    ExaminService service;

    @RequestMapping("/exportExcel/{id}")
    @ResponseBody
    public AjaxResult exportExcel(@PathVariable Integer id) {
        return service.exportExcel(id);
    }

    @RequestMapping("/importExcel")
    public String importExcel(ModelMap map) {
        return service.importExcel(map);
    }


    @RequestMapping("/excel")
    public String excel(ModelMap mm) {
        mm.put("code", CODE);
        return BASE_PATH + "excel1.html";
    }


    @RequestMapping("/excel/{id}")
    public String excelAddex(ModelMap mm, @PathVariable Integer id) {
        mm.put("code", CODE);
        mm.put("examinId", id);
        return BASE_PATH + "excel.html";
    }


    @RequestMapping("/readExcel")
    @ResponseBody
    public AjaxResult readExcel(@RequestParam(value = "excelFile") MultipartFile file, Integer examinId, Integer type) throws Exception {
        if (file != null) {
            byte[] in = file.getBytes();
            if (examinId == null || type == null) {
                return error("添加失败");
            }
            try {
//                Examin examin = new Examin();
//                examin.setType(1);
//                examin.setTitle(file.getName());
//                Blade.create(Examin.class).saveAndSetKey(examin);
                Blade.create(ExaminTopic.class).deleteBy("examineId=#{examinId}", getData("examinId", examinId));
                new ReadExcel().readExcel(file, examinId, type);
                return success("添加成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return error("添加失败");
        }

        return error("添加失败");
    }


    @RequestMapping("/deleteByTopicId/{id}")
    @ResponseBody
    public void deleteByTopicId(@PathVariable Integer id) {
        Blade.create(ExaminTopic.class).delete(id);
        Blade.create(ExaminTopicAnswer.class).deleteBy("topicId=#{id}", getCMap().put("id", id));
    }


    @RequestMapping("/addTitleTopic/{examineId}")
    public String addTitleTopic(@PathVariable Integer examineId, ModelMap mm) {
        mm.put("examineId", examineId);
        mm.put("code", CODE);
        return BASE_PATH + "addTitleTopic.html";
    }

    @RequestMapping("/doTitleTopic")
    @ResponseBody
    public AjaxResult doTitleTopic(Integer examineId, ModelMap mm, String name, String reach, String images, String[] content, String[] result) {
        mm.put("code", CODE);
        return service.saveExamineTopicAnswer(examineId, name, reach, images, content, result, 1);
    }


    @RequestMapping("/title/{id}")
    public String addTitle(@PathVariable Integer id, ModelMap mm, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "1") Integer page) {
        mm.put("code", CODE);
        mm.put("id", id);
        List lists = new ArrayList();
        BladePage<ExaminTopic> paginate = Blade.create(ExaminTopic.class).paginate("select * from t_examin_topic where examineId=#{examineId}", getCMap().put("examineId", id), page, size);
        List<ExaminTopic> topicList = paginate.getRows();
        Integer currentIndex = size * (page - 1);
        for (int i = 0; i < topicList.size(); i++) {
            Map map = new HashMap();
            map.put("id", i + 1 + currentIndex);
            List<ExaminTopicAnswer> answerList = Blade.create(ExaminTopicAnswer.class).findBy("topicId=#{topicId}", getCMap().put("topicId", topicList.get(i).getId()));
            map.put("topic", topicList.get(i));
            if (StringUtils.isNotBlank(topicList.get(i).getImage())) {
                map.put("images", Convert.toStrArray(topicList.get(i).getImage()));
            } else {
                map.put("images", null);
            }

            map.put("answers", answerList);
            lists.add(map);
        }
        mm.put("lists", lists);
        mm.put("paginate", paginate);
        return BASE_PATH + "addTitle.html";
    }


    @RequestMapping(KEY_MAIN)
    public String index(ModelMap mm) {
        mm.put("code", CODE);
        return BASE_PATH + "examin.html";
    }

    @RequestMapping(KEY_ADD)
    public String add(ModelMap mm) {
        mm.put("code", CODE);
        return BASE_PATH + "examin_add.html";
    }

    @RequestMapping(KEY_EDIT + "/{id}")
    public String edit(@PathVariable Integer id, ModelMap mm) {
        Examin examin = service.findById(id);
        mm.put("model", JsonKit.toJson(examin));
        mm.put("id", id);
        mm.put("code", CODE);
        return BASE_PATH + "examin_edit.html";
    }

    @RequestMapping(KEY_VIEW + "/{id}")
    public String view(@PathVariable Integer id, ModelMap mm) {
        Examin examin = service.findById(id);
        mm.put("model", JsonKit.toJson(examin));
        mm.put("id", id);
        mm.put("code", CODE);
        return BASE_PATH + "examin_view.html";
    }

    @ResponseBody
    @RequestMapping(KEY_LIST)
    public Object list() {
        Object grid = paginate(LIST_SOURCE);
        return grid;
    }

    @ResponseBody
    @RequestMapping(KEY_SAVE)
    public AjaxResult save() {
        Examin examin = mapping(PREFIX, Examin.class);
        examin.setType(1);
        boolean temp = service.save(examin);
        if (temp) {
            return success(SAVE_SUCCESS_MSG);
        } else {
            return error(SAVE_FAIL_MSG);
        }
    }

    @ResponseBody
    @RequestMapping(KEY_UPDATE)
    public AjaxResult update() {
        Examin examin = mapping(PREFIX, Examin.class);
        boolean temp = service.update(examin);
        if (temp) {
            return success(UPDATE_SUCCESS_MSG);
        } else {
            return error(UPDATE_FAIL_MSG);
        }
    }

    @ResponseBody
    @RequestMapping(KEY_REMOVE)
    public AjaxResult remove(@RequestParam String ids) {
        int cnt = service.deleteByIds(ids);
        if (cnt > 0) {
            return success(DEL_SUCCESS_MSG);
        } else {
            return error(DEL_FAIL_MSG);
        }
    }
}
